<?php

namespace app\api\admin\v1\service\finder;

use zhanshop\App;
use zhanshop\server\Request;
use zhanshop\server\Response;

class Visitdevice extends BaseFinder
{
    protected $tabs = [
        [
            'title' => '全部应用',
            'where' => [
                'app',
                '=',
                ''
            ],
        ],
    ];

    protected $headToolbar = [];

    protected $rowToolbar = [
        [
            'event' => 'open',
            'ico' => '&#xe640;',
            'title' => '页面访问',
            'method' => '',
            'page' => './simple-table.html?_id=Eventpage',
        ],
    ];

    public function __construct(string $menuId)
    {
        parent::__construct($menuId);
        $apps = App::database()->model("ad_app")->order('create_time asc')->limit(20)->select();
        foreach ($apps as $app){
            $this->tabs[] = [
                'title' => $app['name'],
                'where' => [
                    'app',
                    '=',
                    $app['app']
                ],
            ];
        }
    }

    public function searchfrom(Request $request, Response $response){
        $data = parent::searchfrom($request, $response);
        $tabs = $this->tabs;
        unset($tabs[0]);
        $apps = [];
        foreach ($tabs as $tab){
            $app = $tab['where'][2];
            $apps[$app] = $tab['title'];
        }
        $data['app']['value'] = $apps;
        return $data;
    }

    /**
     * 获取百度图表数据
     * @param string $title
     * @param array $dates
     * @param array $channels
     * @param array $channelDateData
     * @return void
     */
    public static function getEchartsOption(string $title, array $dates, array $channels, array $channelDateData)
    {
        $series = [];
        foreach ($channels as $k => $channel){
            $series[$k] = [
                "name" => $channel['name'],
                "type" => 'line',
                "stack" => 'Total',
                "areaStyle" => [],
                "emphasis" => [
                    "focus" => 'series'
                ],
                "data" => []
            ];
            foreach ($dates as $kk => $date){
                $series[$k]['data'][$kk] = 0;
                if(isset($channelDateData[$channel['name']][$date])){
                    $series[$k]['data'][$kk] = $channelDateData[$channel['name']][$date];
                }
            }
        }

        $option = [
            "title" => [
                "text" => $title
            ],
            "tooltip" => [
                "trigger" => "axis",
                "axisPointer" => [
                    "type" => "",
                    "label" => [
                        "backgroundColor" => "#6a7985"
                    ]
                ]
            ],
            "legend" => [
                "data" => [array_column($channels, 'name')]
            ],
            "toolbox" => [
                "feature" => [
                "saveAsImage" => []
                ]
            ],
            "grid" => [
                "left" => '3%',
                "right" => '4%',
                "bottom" => '3%',
                "containLabel" => true
            ],
            "xAxis" => [
                [
                    "type" => 'category',
                    "boundaryGap" => false,
                    "data" => $dates
                ]
            ],
            "yAxis" => [
                [
                    "type" => 'value'
                ]
            ],
            "series" => $series
        ];
        return $option;
    }

    public function trend(Request $request, Response $response)
    {
        $date = $request->param("dateof");
        $app = $request->param("app");
        if($app == false) App::error("app参数不能为空");
        if($date == false){
            $yesterday = date('Y-m-d', strtotime("-1 day"));
            $date = $yesterday.' - '.$yesterday;
        }

        list($startDate, $endDate) = explode(' - ', $date);
        list($startTime, $endDateTime) = [strtotime($startDate), strtotime($endDate)];
        if(($endDateTime - $startTime) >= 90 * 86400){
            App::error()->setError("最多只能查询90天区间内的数据", 417);
        }

        if(str_replace('-', '', $endDate) > str_replace('-', '', date('Y-m-d', strtotime("-1 day")))){
            App::error()->setError("结束时间不能大于昨日时间", 417);
        }

        $dates = [];
        while (true){
            if($startTime > $endDateTime){
                break;
            }
            $dates[] = date("Y-m-d", $startTime);
            $startTime += 86400;
        }

        $channels = App::database()->model("ad_channel")->where(['app' => $app])->field('app,name')->order("create_time asc")->limit(200)->select();
        $dayData = App::database()->model("visit_day_report")->where(['app' => $app])->whereRaw('channel != "all" and dateof >= "'.addslashes($startDate).'" and dateof <= "'.addslashes($endDate).'"')->order('dateof asc')->limit(20000)->select();

        $channelInstallDateData = [];
        $channelRegisterDateData = [];
        $channelOrderDateData = [];
        $channelPayDateData = [];
        foreach ($channels as $channel){
            foreach ($dayData as $report){
                if($report['channel'] == $channel['name']){
                    $channelInstallDateData[$channel['name']][$report['dateof']] = $report['install'];
                    $channelRegisterDateData[$channel['name']][$report['dateof']] = $report['register'];
                    $channelOrderDateData[$channel['name']][$report['dateof']] = $report['paycall'];
                    $channelPayDateData[$channel['name']][$report['dateof']] = $report['payment'];
                }
            }
        }

        $echartsOptions = [
            self::getEchartsOption("渠道安装趋势", $dates, $channels, $channelInstallDateData),
            self::getEchartsOption("渠道注册趋势", $dates, $channels, $channelRegisterDateData),
            self::getEchartsOption("渠道下单趋势", $dates, $channels, $channelOrderDateData),
            self::getEchartsOption("渠道付费趋势", $dates, $channels, $channelPayDateData),
        ];
        return $echartsOptions;
    }
}